package com.hw.paltfrom.config;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hw.paltfrom.mapper.HwBlacklistCarDetailsMapper;
import com.hw.paltfrom.mapper.HwBlacklistCarMapper;
import com.hw.paltfrom.mapper.HwCaseMainMapper;
import com.hw.paltfrom.mapper.HwDataOverrunstationHistoryMapper;
import com.hw.paltfrom.mapper.HwDataOverrunstationOverweightMapper;
import com.hw.paltfrom.pack.ResponseResult;
import com.hw.paltfrom.pojo.HwBlacklistCar;
import com.hw.paltfrom.pojo.HwBlacklistCarDetails;
import com.hw.paltfrom.pojo.HwCaseMain;
import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.utils.DateTimeUtil;
import com.hw.paltfrom.utils.RandomNumberUtil;

@Configuration
public class ScheduledTaskConfig implements SchedulingConfigurer {

	@Autowired
	private HwDataOverrunstationHistoryMapper dataOverrunstationHistoryMapper;

	@Autowired
	private HwDataOverrunstationOverweightMapper dataOverrunstationOverweightMapper;
	
	
	@Autowired
	private HwCaseMainMapper HwCaseMainMapper;
	
	@Autowired
	private HwBlacklistCarMapper blackCarMapper;
	@Autowired
	private HwBlacklistCarDetailsMapper blackCarDetailsMapper;
	
	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

//		RedisUtil redis = SpringUtil.getBean(RedisUtil.class);
		
		scheduledTaskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				try {
//		
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				String cron = "0 23 0 ? * *";// 23:00执行一次
				if ("".equals(cron) || cron == null)
					return null;
				// 定时任务触发,可修改定时任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExecDate = trigger.nextExecutionTime(triggerContext);
				return nextExecDate;
			}
		});
		
		
		
		
		scheduledTaskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				try {

					System.out.println("《---车辆黑名单定时任务执行---》");// 异步定时操作
					long endTime = System.currentTimeMillis();
					long startTime = DateTimeUtil.getAfterYear(-1);
					// 一年内查执法表 完结的数据
					// Wrapper<HwCaseMain> wrapper = new EntityWrapper<HwCaseMain>();
					// wrapper.eq("F_AJ_CrtStep", "07");
					// wrapper.between("F_CL_CheckTime", startTime, endTime);
					// wrapper.groupBy("F_CL_TruckNo");
					// List<HwCaseMain> selectList = HwCaseMainMapper.selectList(wrapper);

					Calendar StartCalendar = Calendar.getInstance();
					StartCalendar.setTimeInMillis(startTime);
					SimpleDateFormat StartSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String formatStartTime = StartSimpleDateFormat.format(StartCalendar.getTimeInMillis());

					Calendar EndCalendar = Calendar.getInstance();
					EndCalendar.setTimeInMillis(endTime);
					SimpleDateFormat EndSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String formatEndTime = EndSimpleDateFormat.format(EndCalendar.getTimeInMillis());

					List<Map<String, Object>> queryStationGroup = HwCaseMainMapper.queryStationGroup(formatStartTime,
							formatEndTime);

					// 存黑名单车牌号
					ArrayList<String> blackCPHList = new ArrayList<String>();
					for (Map<String, Object> m : queryStationGroup) {
						Object CPH = m.get("F_CL_TruckNo");
						Integer num = Integer.parseInt(m.get("num").toString());
						if (num > 3) {
							blackCPHList.add(CPH.toString());
						}
					}

					// 插入黑名单
					for (String cph : blackCPHList) {
						// 查黑名单是否存在此车信息

						// Wrapper<HwBlacklistCar> blackCarWrapper=new
						// EntityWrapper<HwBlacklistCar>();
						// blackCarWrapper.eq("CPH", cph);
						// List<HwBlacklistCar> blackCarList =
						// blackCarMapper.selectList(blackCarWrapper);
						HwBlacklistCar blackCarentity = new HwBlacklistCar();
						blackCarentity.setCph(cph);
						HwBlacklistCar blackCar = blackCarMapper.selectOne(blackCarentity);

						Wrapper<HwCaseMain> caseMainWrapper = new EntityWrapper<HwCaseMain>();
						caseMainWrapper.eq("F_CL_TruckNo", cph);
						List<HwCaseMain> oldDataList = HwCaseMainMapper.selectList(caseMainWrapper);
						HwCaseMain hwCaseMain = oldDataList.get(0);

						if (blackCar == null) {
							// 没有黑名单信息插入
							HwBlacklistCar newData = new HwBlacklistCar();
							newData.setfId(RandomNumberUtil.getNumber());
							newData.setCph(cph);

							Integer zs = Integer.parseInt(hwCaseMain.getfClAxis());
							newData.setZs(zs.byteValue());

							Double xz = hwCaseMain.getfClLimitweight();
							newData.setXz(xz.byteValue());

							Integer cx = Integer.parseInt(hwCaseMain.getfClTruckmodel());
							newData.setCx(cx.byteValue());

							newData.setItype(new Integer(0).byteValue());
							newData.setCreatetime(new Timestamp(System.currentTimeMillis()));
							newData.setTransferstate(new Integer(0).byteValue());
							newData.setfCreatedate(new Timestamp(System.currentTimeMillis()));
							newData.setfCreateuserid("平台自动");
							newData.setfCreateusername("平台自动");
							Integer insert = blackCarMapper.insert(newData);
							
							HwBlacklistCarDetails carDetails = new HwBlacklistCarDetails();
							carDetails.setfId(RandomNumberUtil.getNumber());
							carDetails.setfBlacklistCar(newData.getfId());
							carDetails.setCph(cph);
							carDetails.setfOverrunid(hwCaseMain.getfOverruncode());
							carDetails.setfOverrunname(hwCaseMain.getfOverrunname());
							carDetails.setCz(new BigDecimal(new Double(hwCaseMain.getfClTotalweight()).toString()));
							carDetails.setCxs(new BigDecimal(new Double(hwCaseMain.getfClOverweight().toString())));
							carDetails.setCreatetime(new Timestamp(System.currentTimeMillis()));
							carDetails.setfZfid(hwCaseMain.getfCaseid());
							carDetails.setjJcsj(hwCaseMain.getfClChecktime());
							Integer insertDetail = blackCarDetailsMapper.insert(carDetails);
						} else {
							// 有黑名单信息更新
							HwBlacklistCar newData = new HwBlacklistCar();
							// newData.setfId(RandomNumberUtil.getNumber());
							newData.setCph(cph);

							Integer zs = Integer.parseInt(hwCaseMain.getfClAxis());
							newData.setZs(zs.byteValue());

							Double xz = hwCaseMain.getfClLimitweight();
							newData.setXz(xz.byteValue());

							Integer cx = Integer.parseInt(hwCaseMain.getfClTruckmodel());
							newData.setCx(cx.byteValue());

							newData.setItype(new Integer(0).byteValue());
							newData.setCreatetime(new Timestamp(System.currentTimeMillis()));
							newData.setTransferstate(new Integer(0).byteValue());
							newData.setfCreatedate(new Timestamp(System.currentTimeMillis()));
							newData.setfCreateuserid("平台自动");
							newData.setfCreateusername("平台自动");

							Wrapper<HwBlacklistCar> wrapper = new EntityWrapper<HwBlacklistCar>();
							wrapper.eq("CPH", cph);
							Integer update = blackCarMapper.update(newData, wrapper);

							// 黑名单插入详情

							HwBlacklistCarDetails carDetails = new HwBlacklistCarDetails();
							carDetails.setfId(RandomNumberUtil.getNumber());
							carDetails.setfBlacklistCar(blackCar.getfId());
							carDetails.setCph(cph);
							carDetails.setfOverrunid(hwCaseMain.getfOverruncode());
							carDetails.setfOverrunname(hwCaseMain.getfOverrunname());
							carDetails.setCz(new BigDecimal(new Double(hwCaseMain.getfClTotalweight()).toString()));
							carDetails.setCxs(new BigDecimal(new Double(hwCaseMain.getfClOverweight().toString())));
							carDetails.setCreatetime(new Timestamp(System.currentTimeMillis()));
							carDetails.setfZfid(hwCaseMain.getfCaseid());
							carDetails.setjJcsj(hwCaseMain.getfClChecktime());
							Integer insert = blackCarDetailsMapper.insert(carDetails);
						}

					}
					
					
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				String cron = "0 23 0 ? * *";// 23:00执行一次
				if ("".equals(cron) || cron == null)
					return null;
				// 定时任务触发,可修改定时任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExecDate = trigger.nextExecutionTime(triggerContext);
				return nextExecDate;
			}
		});

		scheduledTaskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				try {
//					System.out.println("超重定时任务正在执行-------");
//					
//					
//					List<HwDataOverrunstationHistory> all=new ArrayList<HwDataOverrunstationHistory>();
//					
////					动态数据超重   20分钟内没有静态数据
//					Wrapper<HwDataOverrunstationHistory> timeoutWrapper = new EntityWrapper<HwDataOverrunstationHistory>();
//					long afterMinute = DateTimeUtil.getAfterMinute(-20);
//					timeoutWrapper.isNull("J_JCSJ").and().eq("D_SFCX", "1").and().le("D_JCSJ", new Timestamp(afterMinute));
//					List<HwDataOverrunstationHistory> timeout = dataOverrunstationHistoryMapper.selectList(timeoutWrapper);
//					all.addAll(timeout);
//					
////					动态数据超重 静态数据也超重
////					J_SFCZ
//					Wrapper<HwDataOverrunstationHistory> overWrapper = new EntityWrapper<HwDataOverrunstationHistory>();
//					overWrapper.eq("D_SFCX", "1").and().eq("J_SFCZ", "1");
//					List<HwDataOverrunstationHistory> overList = dataOverrunstationHistoryMapper.selectList(overWrapper);
//					all.addAll(overList);
//					
////					无动态  静态超重
//					Wrapper<HwDataOverrunstationHistory> joverWrapper = new EntityWrapper<HwDataOverrunstationHistory>();
//					joverWrapper.isNotNull("D_SFCX").and().eq("J_SFCZ", "1");
//					List<HwDataOverrunstationHistory> joverList = dataOverrunstationHistoryMapper.selectList(joverWrapper);
//					all.addAll(joverList);
//					
//					for(HwDataOverrunstationHistory item:all){
//						HwDataOverrunstationOverweight entity=new HwDataOverrunstationOverweight();
//						entity.setfId(RandomNumberUtil.getNumber());
//						entity.setCph(item.getCph());
//						entity.setdCptx(item.getdCpys());
//						entity.setdZz(item.getdZz().doubleValue());
//						entity.setdXz(item.getdXz().intValue());
//						entity.setdZs(item.getdZs().intValue());
//						entity.setdCx(item.getdCx().intValue());
//						entity.setdCxl(item.getdCxl().doubleValue());
//						entity.setdJcsj(item.getdJcsj());
//						entity.setdCd(item.getdCd().intValue());
//						entity.setdCs(item.getdCs().intValue());
//						entity.setdFx(item.getdFx());
//						entity.setdSfcx(item.getdSfcx());
//						entity.setdCptx(item.getdCptx());
//						entity.setdCttx(item.getdCttx());
//						entity.setdCreatetime(item.getdCreatetime());
//						entity.setjZz(item.getjZz().doubleValue());
//						entity.setjSfcz(item.getjSfcz().intValue());
//						entity.setjCxds(item.getjCxds().doubleValue());
//						entity.setjCzy(item.getjCzy());
//						entity.setjJcsj(item.getjJcsj());
//						entity.setjCreatetime(item.getjCreatetime());
//						entity.setjCtpic(item.getjCtpic());
//						entity.setjCspic(item.getjCspic());
//						entity.setjCwpic(item.getjCwpic());
//						entity.setjCppic(item.getjCppic());
//						entity.setfAreacode(item.getfAreacode());
//						entity.setfOverruncode(item.getfOverruncode());
//						entity.setfOverrunname(item.getfOverrunname());
//						entity.setIsSeized(0);
//						dataOverrunstationOverweightMapper.insert(entity);
//					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// Object object = redis.get("逃逸任务开始时间");
				// Object object = redis.get("督导任务执行次数");
//				String cron = "0 */1 * * * ?";// 每分钟执行1次
//				String minuteCron = getMinuteCron("1");
//				if ("".equals(minuteCron) || minuteCron == null)
//					return null;
				
				String cron = "0 23 0 ? * *";// 23:00执行一次
				if ("".equals(cron) || cron == null)
					return null;
				// 定时任务触发,可修改定时任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExecDate = trigger.nextExecutionTime(triggerContext);
				return nextExecDate;
			}
		});
	}

	// 几分钟执行一次
	private String getMinuteCron(String minute) {
		StringBuffer cron = new StringBuffer();
		cron.append("0 */");
		cron.append(minute);
		cron.append(" * * * ?");
		return cron.toString();

	}

	// 固定时间开始执行

	@SuppressWarnings("unused")
	private String getTimeCron(long timestamp) {
		StringBuffer cron = new StringBuffer();
		DateTimeFormatter ftf = DateTimeFormatter.ofPattern("HH:mm:ss");
		String format = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()));
		String[] split = format.split(":");
		cron.append(split[2]);
		cron.append(" ");
		cron.append(split[1]);
		cron.append(" ");
		cron.append(split[0]);
		cron.append(" ? * *");
		return cron.toString();
	}
	
}
